package com.delivery.www.servlet;

import com.alibaba.fastjson.JSON;
import com.delivery.www.po.Cart;
import com.delivery.www.po.Dish;
import com.delivery.www.po.User;
import com.delivery.www.service.ServiceImpl.CartDishServiceImpl;
import com.delivery.www.service.ServiceImpl.CartServiceImpl;
import com.delivery.www.constant.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 12970
 */
public class CartServlet extends BaseServlet {
    CartServiceImpl cartService = new CartServiceImpl();
    CartDishServiceImpl cartDishService = new CartDishServiceImpl();

    /**
     * 购物车
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void doCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null) {
            writer.print("login");
        } else {
            int storeId = Integer.parseInt(req.getParameter("storeId"));
            int dishId = Integer.parseInt(req.getParameter("dishId"));
            Cart cart = cartService.judgeCart(user.getUserId(), storeId);
            if (cart==null){
                writer.print("error");
            }else {
                boolean b = cartDishService.addCartDish(cart.getCartId(), dishId);
                if (b) {
                    writer.print("ok");
                } else {
                    writer.print("error");
                }
            }
        }
    }

    /**
     * 获取购物车
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void selectCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        List<Cart> allCart = cartService.getAllCart(user.getUserId());
        List<List<Dish>> cartDish = cartDishService.getCartDish(allCart);
        writer.print(JSON.toJSONString(cartDish));
    }

}
